<?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2018/10/30
 * Time: 13:13
 */
use app\assets\AppAsset;
use app\common\CommonHelper;

$base = Yii::$app->request->baseUrl;
AppAsset::addCss($this,$base . '/app/css/vest-list.css');

AppAsset::addCss($this,$base . '/css/jquery.Jcrop.css');
AppAsset::addScript($this,$base . '/js/jquery.Jcrop.min.js');

$model = new CommonHelper();
$baseUrlHead  = $model->getIp();
?>

<div class="search-box">
    <div class="datep" style="margin-left: 35.67rem;"><input id="nameId" class="name-input" placeholder="请输入"></div>

    <img id="search-img" onclick="searchFunction()" class="search-icon" style="margin-left: 1.67rem;" src="<?=$base?>/app/images/new/rc_btn_search_n.png">

        <div class="button-div" style="margin-left: 3.6rem" onclick="showDialog()">新增</div>

    <div style="clear:both;"></div>
</div>

<div id="add-gift" class="dialog-topic" hidden="hidden">
    <div class="topic-box">
        <p>礼物添加</p>

        <input id="giftName" placeholder="输入礼物名称" maxlength="10">

        <br>

        <div class="img-div" style="width: auto;height: auto;" id="upload2" onclick="showPic()">
            <img style="width: 8.3rem;height: 8.3rem;margin: 0.8rem"  id="img" src="<?= $base?>/app/images/dynamic/default-logo.png">
            <input type="file" accept="image/jpg,image/jpeg,image/png" id="upload-file2" name="upload-file2" onchange="thumbImage(this)" style="display: none">
        </div>

        <input style="margin-top: 1.67rem" id="giftPirce" placeholder="输入礼物热币" oninput = "value=value.replace(/[^\d]/g,'')">

        <div class="footer-div">
            <div class="button-div" onclick="createGiftController.createGiftFunc()">确定</div>
            <div class="button-div" style="margin-left: 1.5rem" onclick="hideDialog()">取消</div>
        </div>
    </div>
</div>

<div id="edit-gift" class="dialog-topic" hidden="hidden"> 
    <div class="topic-box"> 
        <p>礼物编辑</p> 

        <input id="gifttempName"  maxlength="10" value=""> 
        <br> 

        <div class="img-div" style="width: auto;height: auto;" id="upload2" onclick="showPic()">
            <img style="width: 8.3rem;height: 8.3rem;margin: 0.8rem"  id="image" src="">
            <input type="file" accept="image/jpg,image/jpeg,image/png" id="upload-file2" name="upload-file2" onchange="thumbImage(this)" style="display: none">
        </div> 
        <input style="margin-top: 1.67rem" id="gifttempPirce" value="" oninput = "value=value.replace(/[^\d]/g,'')"> 
        <div class="footer-div"> 
            <div class="button-div" id="goedit">确定</div>
            <div class="button-div" style="margin-left: 1.5rem" onclick="hideEdit()">取消</div> 
        </div> 
    </div> 
</div>

<div id = "a"></div>

<div class="table-box" style="background: none">
    <table id="table" style="background: #FFFFFF;"></table>
</div>

<script>
    //初始化表格设置
    $('#table').bootstrapTable({
//        height: 525,//高度
        toolbar: '#toolbar',        //工具按钮用哪个容器
        clickToSelect: true,//点击行即可选中单选/复选框
        singleSelect: false,//复选框只能选择一条记录
        search: false,//是否显示右上角的搜索框
        striped: true,      //是否显示行间隔色
        cache: false,            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sidePagination: "server", //服务端处理分页
        pagination: true,     //是否显示分页（*）
        sortable: false,           //是否启用排序
        sortOrder: "asc",          //排序方式
        method: 'GET',      //请求方式（*）
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: 8,      //每页的记录行数（*）
//        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        cardView: false,          //是否显示详细视图
        queryParams:setParams,
        uniqueId:'gifttemp_code',
        url:'gifttemps',
        responseHandler:dataProcess,

        columns: [{
            field: 'gifttemp_code',
            align: 'center',
            valign: 'middle',
            title: '奖品次序'
        },{
            field: 'gifttemp_name',
            align: 'center',
            valign: 'middle',
            title: '奖品名称'
        },{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '奖品图',
            formatter:function(value,row,index) {
                var html = "";

                html = '<div class="image-item" style="cursor: pointer" onclick="showPic('+ row.gifttemp_pic +')"><img class="image-value" src='+ row.gifttemp_pic +' style="width:80px; height:80px;" ></div>';
                return html;
            }
        },{
            field: 'gifttemp_pirce',
            align: 'center',
            valign: 'middle',
            title: '所需热币'
        },{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '状态',
            formatter:function(value,row,index) {
                if (row.is_deleted == 0) {
                    return "正常";
                } else {
                    return "下架";
                }
            }
        },{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '操作',
            formatter:function(value,row,index) {
                var html = "";
                if(row.is_deleted == 0){
                    html = '<div style="display:inline-block" class="btn_cancel" onclick="editStatus('+row.gifttemp_code+',1)">下架</div> <div style="display:inline-block" class="btn_cancel" onclick="giftEdit('+row.gifttemp_code+')">编辑</div>'
                }else{
                    html = '<div style="display:inline-block" class="btn_cancel" onclick="editStatus('+row.gifttemp_code+',0)">上架</div> <div style="display:inline-block" class="btn_cancel" onclick="giftEdit('+row.gifttemp_code+')">编辑</div>'
                }

                return html;
            }
        }]
    });

    function dataProcess(res){
        var data = res;
        return {
            'rows':data.rows,
            'total':data.total
        }
    }

    var userSex = -1;

    function setParams(params){

        if (userSex != -1){
            params.user_sex = userSex;
        }

        var content = $("#nameId").val();

        if (content && content != undefined && content.length > 0){
            params.user_name = content;
        }

        return params;
    }

    function chooseUserSex(name,sex){
        userSex = sex;
        $("#dropdownMenu").text(name);
        $('#table').bootstrapTable('refreshOptions', {pageNumber: 1});
    }

    function searchFunction(){
        $('#table').bootstrapTable('refreshOptions', {pageNumber: 1});
    }

    // 显示添加页面
    function showDialog(){
        $("#add-gift").show();
    }

    // 隐藏添加页面
    function hideDialog(){
        $("#add-gift").hide();
    }

    // 加载编辑页面请求
    function giftEdit(gifttemp_code){
        var giftEdits = "gift-edit";
        var param = {'gifttemp_code' : gifttemp_code};
        sendAjax(giftEdits,"POST",param,false,function(res){
            if(res){
                // 将json格式数据转换成数组格式
                row = JSON.parse(res);
                // 给input表单赋值
                $("#gifttempName").val(row.gifttemp_name);
                $("#gifttempPirce").val(row.gifttemp_pirce);
                // 给img赋予路径src
                $("#image").attr('src',row.gifttemp_pic);
                // 给确定按钮赋予点击编辑事件
                $("#goedit").on("click", function () {
                    var goEdit = "gifttemps";
                    var userAvatar = $("#image").attr("src");
                    var userName = $("#gifttempName").val();
                    var userPirce = $("#gifttempPirce").val();

                    if(userName == row.gifttemp_name && userPirce == row.gifttemp_pirce && userAvatar == row.gifttemp_pic){
                        alert("请改点东西吧");
                        return;
                    }

                    if(userAvatar.indexOf("http") == -1){
                        alert("请上传头像");
                        return;
                    }

                    if(userName.length == 0){
                        alert("请输入昵称");
                        return;
                    }

                    if(userPirce.length == 0){
                        alert("请输入热币");
                        return;
                    }

                    var param = {
                        gifttemp_pic: userAvatar,
                        gifttemp_name:userName,
                        gifttemp_pirce:userPirce,
                        gifttemp_code:row.gifttemp_code
                    };

                    $(".loading-area").show();
                    sendAjax(goEdit, "POST", param, false, function(data){
                        var res = JSON.parse(data);
                        if (res.code == 0) {
                            location.reload();
                        } else {
                            alert(res.msg);
                        }
                    });
                });

                $("#edit-gift").show();
            }else {
                alert(res);
            }
        });
    }

    // 隐藏加载页面
    function hideEdit(){
        $("#edit-gift").hide();
    }

    var createGiftController = {
        createGiftApi:'add-gift',
        createGiftFunc : function(){

            // var mobile = "168168" + Math.round(new Date().getTime()/1000).toString();

            var userAvatar = $("#img").attr("src");
            if(userAvatar.indexOf("http") == -1){
                alert("请上传头像");
                return;
            }

            var userName = $("#giftName").val();
            if(userName.length == 0){
                alert("请输入昵称");
                return;
            }

            var userPirce = $("#giftPirce").val();
            if(userPirce.length == 0){
                alert("请输入热币");
                return;
            }

            var param = {
                // mobile:mobile,
                gifttemp_pic: userAvatar,
                gifttemp_name:userName,
                gifttemp_pirce:userPirce
            };

            $(".loading-area").show();
            sendAjax(this.createGiftApi,"post",param,false,function(res){
                if(res.code != 0){
                    location.reload();
                }else
                    alert(res.msg);
            });
        }
    }

    function goToDetail(user_id, menuitemid){
        window.open("vest-detail?user_id="+user_id+"&menuitemid="+menuitemid);
    }

    function goToChat(user_id){
        window.open("chatlist-party?user_id="+user_id);
    }
</script>

<script>
    $(function(){
//选择图片点击事件
        $(".myClose").click(function(){
            closePic();
        });
        $(".select-img").click(function(){
            upload(this);
        });
        $(".upload-img").click(function(){
            uploadImage(this);
        });
        //选择图片结束
    });

    //点击图片来选择上传的图片
    function upload(button){
//        $(button).css('background-color','#77778F').css('color','white');
        var intputId = 'upload-file2';
        document.getElementById(intputId).click();
    }

    function showPic(){
        $('.choose-area').show();
    }

    function closePic(){
        $('.choose-area').hide();
        $('.pic-area').empty();
        if (!$('.pic-area img').length){
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        $('.upload').css('background-color','white').css('color','#A8A8A8');
        $('.select-img').css('background-color','white').css('color','#A8A8A8');
        //清除input file 的value,可以触发下次的onchange;
        $('#upload-file2').val('');

        $('.upload-img').css('background','white').prop('disabled',false);

    }
    //选择图片之后的操作

    //图片缩略图处理
    function thumbImage(input){
        //设置宽高比
        var w = 1;
        var h = 1;

        //再次点击上传时清除之前的截图操作
        if ($('.jcrop-holder').length){
            $('.pic-area').empty();
            $('.pic-area').prepend('<img class="pic-area-img" id="pic-area-img" >');
        }
        if (typeof (FileReader) != "undefined") {
            var regex = /(.jpg|.jpeg|.png)$/;
            $($(input)[0].files).each(function () {
                var file = $(this);
                if (regex.test(file[0].name.toLowerCase())) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
//                        var img = $(input).prev();
                        var img = $('#pic-area-img');
                        $(img).attr('src',e.target.result);
                        var realWidth;//真实的宽度
                        var realHeight;//真实的高度
                        //这里做下说明，$("<img/>")这里是创建一个临时的img标签，类似js创建一个new Image()对象！
                        $("<img/>").attr("src", $(img).attr('src')).load(function() {
                            /*
                             如果要获取图片的真实的宽度和高度有三点必须注意
                             1、需要创建一个image对象：如这里的$("<img/>")
                             2、指定图片的src路径
                             3、一定要在图片加载完成后执行如.load()函数里执行
                             */
                            realWidth = this.width;
                            realHeight = this.height;
                            var width = $('.pic-area').css('width').split('p')[0];
                            var height = $('.pic-area').css('height').split('p')[0];
//                            console.log(realWidth,realHeight,width,height)
                            if(realWidth<width && realHeight<height){
                                $(img).css("width",realWidth+'px').css("height",realHeight+'px');
                            }else{
                                //如果真实的宽高比大于给定的宽高比就按照宽度100%显示
                                if(realWidth/realHeight >= width/height){
                                    $(img).css("width","99%").css("height","auto");
                                }
                                else{//如果小于给定的宽高比按照原尺寸显示
                                    $(img).css("width","auto").css("height","99%");
                                }
                            }
//                            console.log(realWidth,$(img).css("width").split('p')[0]);
                            var ratio = realWidth/$(img).css("width").split('p')[0];
//                            console.log(ratio)
                            $('#pic-area-img').show();
                            var jcrop_api;
                            $('#pic-area-img').Jcrop({
                                aspectRatio: w / h,
                                onSelect:uodateCoords,
                                setSelect:[0,0,600,600]
                            },function(){
                                jcrop_api = this;
                            });
                            function uodateCoords(c){
                                $('#x').val(c.x*ratio);
                                $('#y').val(c.y*ratio);
                                $('#w').val(c.w*ratio);
                                $('#h').val(c.h*ratio);
                            }
                            var jcropWidth =   $(img).css('width').split('p')[0];
                            var jcropHeight =   $(img).css('height').split('p')[0];
                            var marginLeft = (width-jcropWidth)/2;
                            var marginTop = (height-jcropHeight)/2;
//                            $('.jcrop-holder').css("margin-top",marginTop + 'px');
                            $('.jcrop-holder').css("margin-left",marginLeft + 'px');
//                            jcrop_api.setSelect([marginLeft,marginTop,336,336]);
                        });
                    }
                    reader.readAsDataURL(file[0]);
                }else {
                    alert(file[0].name + " is not a valid image file.");
                    return false;
                }
            })
        }else{
            alert("This browser does not support HTML5 FileReader.");
        }
    }
    //ajax 异步上传图片
    function uploadImage(button){
        //定义允许上传的图片格式 在前台就可以直接判断，不合法的格式将不会上传
        //尺寸限制

        var intputId = 'upload-file2';
        var limit = 8 * 1024 * 1024;

        var file = $('#'+intputId).get(0).files;

//            $($(button).parent().prev().children()[1]).get(0).files;
        var filetype = ['jpg','jpeg','png','gif'];
        if(file.length){
            var fi = file[0]; //得到文件信息
            //判断文件格式是否是图片 如果不是图片则返回false
            var index = fi.name.lastIndexOf('.');
            var fname = [fi.name.substring(0,index),fi.name.substring(index+1)];
            if(filetype.indexOf(fname[1].toLowerCase()) == -1){
                alert('文件格式不支持');
                return ;
            }
            //实例化h5的fileReader
            var fr = new FileReader();
            fr.readAsDataURL(fi); //以base64编码格式读取图片文件
            fr.onload = function(frev){
                pic = frev.target.result; //得到结果数据
                //开始上传之前，预览图片
//                $('#img').attr('src',pic);
                //使用ajax 利用post方式提交数据
                var x = $('#x').val();
                var y= $('#y').val();
                var width= $('#w').val();
                var height= $('#h').val();
                if (width == 0 && height == 0){
                    alert('请选择图片');
                    return;
                }
                if(fi.size > limit){
                    alert("上传照片不得大于8M");
                    return;
                }
                $('.loading-area').show();
                $(button).css('background','#CCCCCC').prop('disabled',true);
                $.post(
                    'img-upload',
                    {
                        message:pic,
                        filename:fname[0],
                        filetype:fname[1].toLowerCase(),
                        filesize:fi.size,
                        x:x,
                        y:y,
                        width:width,
                        height:height,
                        limit:limit
                    },
                    function(data){
                        data = eval('('+data+')');
                        if(data.code == 1){
                            $('.loading-area').hide();
                            alert('上传失败');
                        }else if(data.code == 0){
                            $("#img").attr("src",data.imgSrc);
                            $("#image").attr("src",data.imgSrc);

                            $('.loading-area').hide();
                            alert('上传成功');
                            closePic();
                        }else if(data.code == 2){
                            var size = parseInt(parseInt(data.size)/1000);
                            if (size>1000)
                                size = parseInt(size/1000) + 'M';
                            else
                                size += 'KB';
                            var msg = data.msg + ',当前图片尺寸为:' + size;
                            $('.loading-area').hide();
                            alert(msg);
                        }
                    }
                )
                    .fail(function(xhr,status,error){
//                    console.log(xhr,status,error)
                        $('.loading-area').hide();
                        alert('上传失败')
                    })
            }
        }else
            alert('请选择图片');
    }

    // ajax修改礼物状态
    function editStatus(gifttemp_code, is_deleted){
        gifttemps = "gifttemps";
        if (confirm('确认修改该状态？')) {
            var param = {
                gifttemp_code : gifttemp_code, 
                status : is_deleted
            };
            $(".loading-area").show();

            sendAjax(this.gifttemps,"POST",param,false,function(res){
                if(res.code != 0){
                    console.log(res);
                    location.reload();
                }else {
                    alert(res);
                }
            });
        }
    }
</script>